package cc.zy.base.hr.controller;


import cc.zy.base.common.annotation.ControllerEndpoint;
import cc.zy.base.common.exception.FebsException;
import cc.zy.base.hr.entity.*;
import cc.zy.base.hr.service.IHrDeptService;
import cc.zy.base.common.controller.BaseController;
import cc.zy.base.common.entity.FebsResponse;
import cc.zy.base.common.entity.QueryRequest;
import cc.zy.base.hr.service.IHrDeptSynLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.bean.WxCpDepart;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 部门
 * Controller
 *
 * @author cheng
 * @date 2022-03-09 10:51:13
 */
@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
@RequestMapping("hrDeptController")
public class HrDeptController extends BaseController {

    @Resource
    private final IHrDeptService deptService;

    @Autowired
    private final IHrDeptSynLogService logService;

    /**
     *日志同步成功对应值
     */
    private static Integer STATUS_HRDEPT_SYNC_SUCCESS;

    /**
     *日志同步失败对应值
     */
    private static Integer STATUS_HRDEPT_SYNC_FAIL;

    /**
     *同步日志手动同步对应值
     */
    private static Integer MODE_HRDEPT_SYNC_MANUAL;
    /**
     * 时间格式
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");


    /**
     * 查询部门
     * @param request
     * @param hrDept
     * @return
     */
    @GetMapping("findList")
    @ResponseBody
    public FebsResponse findDeptList(QueryRequest request, HrDept hrDept) {
        log.debug("前台传来的对象是：" + hrDept);
        Map<String, Object> dataTable = getDataTable(deptService.findHrDepts(request, hrDept));

        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 拉取企业微信部门
     * @return
     */
    @GetMapping("deptList")
    @ResponseBody
    public FebsResponse getHrDeptList(){
        getGenderIdAndStatusId();
        WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
        // 设置微信企业号的appid
        config.setCorpId("wwa431d9d8b2604992");
        // 设置微信企业号的app corpSecret
        config.setCorpSecret("DbpsPO9DgrZlJ-P2c5ElvWZXA7IzOgAv6pnNDuehftk");

        WxCpServiceImpl wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(config);
        List<WxCpDepart> departList = new ArrayList<>();

        HrDeptSynLog hrDeptSynLog = new HrDeptSynLog();


        PrintStream oldPrintStream = System.out;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        HrDeptSynLog hrDeptSynLog1 = new HrDeptSynLog();
        String filePath = getLogUrl(simpleDateFormat.format(new Date()));
        try {
            System.setOut(new PrintStream(bos));
            departList = wxCpService.getDepartmentService().list(null);
            log.debug("对象是" + departList);
            //微信拉取
            List<String> weComDeptIDList = new ArrayList<>();
            for(WxCpDepart listHrDept : departList){
                weComDeptIDList.add(listHrDept.getName());
            }
            //数据库里查询
            List<HrDept> allHrDept = deptService.getAllHrDept();
            List<String> allHrDeptName = new ArrayList<>();
            for (HrDept hrDept : allHrDept) {
                allHrDeptName.add(hrDept.getDeptName());
            }
            //对比是否存在，不存在就删除
            for (String hrDeptName : allHrDeptName) {
                if(!weComDeptIDList.contains(hrDeptName)){
                    deptService.deleteByName(hrDeptName);
                }
            }

            String leader = "";
            for (WxCpDepart depart : departList) {

                HrDept hrDept = new HrDept();

                hrDept.setId(Math.toIntExact(depart.getId()));

                hrDept.setDeptName(depart.getName());
                hrDept.setParentId(Math.toIntExact(depart.getParentId()));

                String[] leaderList = depart.getDepartmentLeader();
                //判断负责人是否为空，将多个负责人名字取出来
                if (leaderList.length != 0) {
                    for (String s : leaderList) {
                        String userName = deptService.getNameByWxUserId(s);
                        leader = leader + userName +"、";
                    }
                    leader = leader.substring(0, leader.length()-1);
                    hrDept.setDepartmentLeader(leader);
                } else {
                    hrDept.setDepartmentLeader("暂无负责人");
                }
                leader = "";
                hrDept.setOrder(depart.getOrder());
                hrDept.setLastModifyDate(new Date());
                //判断部门是否存在，存在就更新，反之同步
                if(deptService.hrDeptExist(hrDept)){
                    deptService.updateHrDeptById(hrDept);
                }else {
                    hrDept.setLastModifyDate(new Date());
                    deptService.savedept(hrDept);
                }
            }
            //同步成功日志
            hrDeptSynLog.setSyncMode(MODE_HRDEPT_SYNC_MANUAL);
            hrDeptSynLog.setStatus(STATUS_HRDEPT_SYNC_SUCCESS);
            hrDeptSynLog.setSyncTime(new Date());
            hrDeptSynLog.setSyncUrl(filePath);
            logService.createDrDeptSynLog(hrDeptSynLog);

        }catch (Exception e) {
            //同步失败日志
            hrDeptSynLog.setSyncMode(MODE_HRDEPT_SYNC_MANUAL);
            hrDeptSynLog.setStatus(STATUS_HRDEPT_SYNC_FAIL);
            hrDeptSynLog.setSyncTime(new Date());
            hrDeptSynLog.setSyncUrl(filePath);
            logService.createDrDeptSynLog(hrDeptSynLog);

            e.printStackTrace();
        } finally {
            System.setOut(oldPrintStream);
        }

        //将日志写入文件
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(filePath);
            fileOutputStream.write(bos.toByteArray());
            //关闭连接
            fileOutputStream.close();
            bos.close();
            oldPrintStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new FebsResponse().success().data(new Date());
    }

    public void getGenderIdAndStatusId(){
        if (STATUS_HRDEPT_SYNC_SUCCESS != null) {
            return;
        }
        STATUS_HRDEPT_SYNC_SUCCESS = deptService.getConstantId("同步成功");
        STATUS_HRDEPT_SYNC_FAIL = deptService.getConstantId("同步失败");
        MODE_HRDEPT_SYNC_MANUAL = deptService.getConstantId("手动同步");
    }

    /**
     * 生成日志的路径及文件名
     * @param fileName
     * @return
     */
    String getLogUrl(String fileName){
        return "src/main/resources/logs/"+fileName+".log";
    }


    @Resource
    private final IHrDeptService hrDeptService;

    @GetMapping("select/tree")
    @ControllerEndpoint(exceptionMessage = "获取部门树失败")
    @ResponseBody
    public FebsResponse getDeptTree() throws FebsException {
        List<HrDeptTree<HrDept>> dept = this.hrDeptService.findDept();
        return new FebsResponse().success().data(dept);
    }
}